<template>
  <el-form label-position="left"  style="margin-top: 50px" label-width="0px" :rules="rules" ref="form" :model="form">
    <el-form-item prop="mail">
      <el-input type="text" v-model.lazy="form.mail"
                auto-complete="off" placeholder="请输入邮箱" style="width: 70%;float: left"></el-input>
      <el-button v-if="buttonFlag" @click="sendCode" style="float: right;width: 120px" :loading="loading">{{ this.content }}</el-button>
      <el-button v-if="!buttonFlag" style="float: right;width: 110px">{{ this.content }}</el-button>
    </el-form-item>
    <el-form-item>
      <el-input type="text" v-model.lazy="authCode"
                auto-complete="off" placeholder="请输入验证码" style="margin-top: 20px"></el-input>
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button type="primary" style="margin-top:20px ; width: 80%;background: #505458;border: none" v-on:click.stop="nextStep">下一步</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import api from '../../apis/login'
import {Message} from 'element-ui'
import {valiDate} from '../../util/verify/valiDate'
import {mailRules} from '../../util/verify/rules'
export default {
  name: 'step2',
  data () {
    return {
      content: '获取验证马',
      rules: mailRules,
      authCode: '',
      form: {
        mail: ''
      },
      timeCode: 60,
      buttonFlag: true,
      loading: false,
      canClick: true // 添加canClick节流防止重复点击
    }
  },
  methods: {
    async sendCode () {
      const _this = this
      /* 执行表单验证 */
      const valid = await valiDate(_this, 'form')
      if (!valid) {
        return null
      }
      this.loading = true
      const resultSend = await api.sendCode(this.form.mail)
      if (resultSend.code === 200) { Message.success(resultSend.msg) } else { Message.error(resultSend.msg) }
      this.loading = false
      this.changeButton()
    },
    changeButton () {
      if (!this.canClick) {
        return
      }
      this.buttonFlag = false
      this.canClick = false
      this.content = this.timeCode + 's'
      let clock = window.setInterval(() => {
        this.timeCode--
        this.content = this.timeCode + 's'
        if (this.timeCode < 0) {
          window.clearInterval(clock)
          this.content = '重新发送'
          this.timeCode = 60
          this.canClick = true // 这里重新开启
        }
      }, 1000)
    },
    async nextStep () {
      this.$emit('authCode', this.authCode, this.form.mail)
      this.$emit('steps')
    }
  }
}
</script>

<style scoped>
.el-button{
  padding: 12px 12px;
}
</style>
